import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

// 基础响应格式
export interface ApiResponse<T> {
  success: boolean
  data: T
  message: string
  timestamp: string
}

// 分页响应格式
export interface PaginatedResponse<T> {
  items: T[]
  total: number
  page: number
  pageSize: number
}

// 错误格式
export interface ApiError {
  code: string
  message: string
  details?: any
}

// 创建axios实例
const apiClient: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    
    console.log('API Request:', config.method?.toUpperCase(), config.url, config.params)
    return config
  },
  (error) => {
    console.error('API Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('API Response:', response.config.method?.toUpperCase(), response.config.url, response.status)
    return response
  },
  (error) => {
    console.error('API Response Error:', error.response?.config?.method?.toUpperCase(), error.response?.config?.url, error.response?.status)
    
    if (error.response?.status === 401) {
      // 跳转到登录页
      window.location.href = '/login'
    }
    
    // 统一错误处理
    const message = error.response?.data?.message || error.message
    return Promise.reject(new Error(message))
  }
)

// 通用请求方法
export async function apiRequest<T>(
  config: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  try {
    const response = await apiClient.request<ApiResponse<T>>(config)
    return response.data
  } catch (error) {
    console.error('API Request Failed:', error)
    throw error
  }
}

// GET请求
export async function get<T>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  return apiRequest<T>({
    method: 'get',
    url,
    params,
    ...config,
  })
}

// POST请求
export async function post<T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  return apiRequest<T>({
    method: 'post',
    url,
    data,
    ...config,
  })
}

// PUT请求
export async function put<T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  return apiRequest<T>({
    method: 'put',
    url,
    data,
    ...config,
  })
}

// DELETE请求
export async function del<T>(
  url: string,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  return apiRequest<T>({
    method: 'delete',
    url,
    ...config,
  })
}

// 文件上传
export async function upload<T>(
  url: string,
  file: File,
  additionalData?: any,
  config?: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  const formData = new FormData()
  formData.append('file', file)
  
  if (additionalData) {
    Object.keys(additionalData).forEach(key => {
      formData.append(key, additionalData[key])
    })
  }
  
  return apiRequest<T>({
    method: 'post',
    url,
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    ...config,
  })
}

export default apiClient